package com.dating.libs.client.parttern.asa;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.annotation.SuppressLint;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public abstract class ADbSqlHelper extends SQLiteOpenHelper {
	public static final String TAG="abstract class: ADbSqlHelper";
	
	// The Android's default system path of your application database.
	@SuppressLint("SdCardPath")
	private static String DB_PATH = "";

	private static String DB_NAME = "dating.sqlite";

	private SQLiteDatabase myDataBase;

	private final Context myContext;

	/**
	 * Constructor Takes and keeps a reference of the passed context in order to
	 * access to the application assets and resources.
	 * 
	 * @param context
	 */
	public ADbSqlHelper(Context context) {
		super(context, DB_NAME, null, 1);
		this.myContext = context;
		DB_PATH="/data/data/"+context.getPackageName()+"/databases/";
		myDataBase=this.getWritableDatabase();
		
		try {
			createDataBase();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * Creates a empty database on the system and rewrites it with your own
	 * database.
	 * */
	public void createDataBase() throws IOException {
		try{
		boolean dbExist = checkDataBase();
		SQLiteDatabase db_Read=null;
		
		if (dbExist) {
			// do nothing - database already exist
		} else {

			// By calling this method and empty database will be created into
			// the default system path
			// of your application so we are gonna be able to overwrite that
			// database with our database.
			
			// before is here! move to end!
			db_Read=this.getWritableDatabase();
//			db_Read.close();
			try {
				
				copyDataBase();
//				db_Read=this.getReadableDatabase();
				db_Read.close();
				
				
			} catch (IOException e) {

				throw new Error("Error copying database");

			}
		}
		
		try{
			myDataBase=this.getReadableDatabase();
	    	//test for exist table
			if(!myDataBase.isOpen()) myDataBase=this.getReadableDatabase();
			myDataBase.execSQL("SELECT * FROM test");
			myDataBase.execSQL("INSERT INTO test VALUES ('0','asdf','adf','asdf')");
			myDataBase.execSQL("INSERT INTO tbl_user VALUES ('0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0')");
        }catch(SQLiteException e){
        	createOldDb(myDataBase);
        }catch (NullPointerException e) {
        	e.printStackTrace();
			Log.e(TAG, "myDataBase null");
			createOldDb(myDataBase);
		}finally{
			myDataBase.close();
		}
		}catch(NullPointerException e){
			e.printStackTrace();
		}
	}

	/**
	 * Check if the database already exist to avoid re-copying the file each
	 * time you open the application.
	 * 
	 * @return true if it exists, false if it doesn't
	 */
	private boolean checkDataBase() {
		File dir = new File(DB_PATH);
		if (!dir.isDirectory())
			dir.mkdirs();
		File file = new File(DB_PATH, DB_NAME);
		if (!file.isFile())
			try {
				file.createNewFile();
			} catch (IOException e1) {
				e1.printStackTrace();
				return false;
			}
		SQLiteDatabase checkDB = null;

		try {
			String myPath = DB_PATH + DB_NAME;
			checkDB = SQLiteDatabase.openDatabase(myPath, null,
					SQLiteDatabase.NO_LOCALIZED_COLLATORS);	//Fix: SELECT locale FROM android_metadata failed
			
		} catch (SQLiteException e) {

			// database does't exist yet.

		}

		if (checkDB != null) {

			checkDB.close();

		}

		return checkDB != null ? true : false;
	}

	/**
	 * Copies your database from your local assets-folder to the just created
	 * empty database in the system folder, from where it can be accessed and
	 * handled. This is done by transferring byteStream.
	 * */
	private void copyDataBase() throws IOException {

		// Open your local db as the input stream
		InputStream myInput = myContext.getAssets().open(DB_NAME);

		// Path to the just created empty db
		String outFileName = DB_PATH + DB_NAME;

		// Open the empty db as the output stream
		OutputStream myOutput = new FileOutputStream(outFileName);

		// transfer bytes from the inputfile to the outputfile
		byte[] buffer = new byte[1024];
		int length;
		while ((length = myInput.read(buffer)) >0) {
			myOutput.write(buffer, 0, length);
		}

		// Close the streams
		myOutput.flush();
		myOutput.close();
		myInput.close();
	}
	
	public void openDataBase() throws SQLException {

		// Open the database
		String myPath = DB_PATH + DB_NAME;
		myDataBase = SQLiteDatabase.openDatabase(myPath, null,
				SQLiteDatabase.NO_LOCALIZED_COLLATORS);

	}

	@Override
	public synchronized void close() {

		if (myDataBase != null)
			myDataBase.close();

		super.close();

	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		try {
			createDataBase();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

	}

	// Add your public helper methods to access and get content from the
	// database.
	// You could return cursors by doing "return myDataBase.query(....)" so it'd
	// be easy
	// to you to create adapters for your views.
	
	private void createOldDb(SQLiteDatabase db){
		if(!db.isOpen()){
			db=this.getWritableDatabase();
		}
		try{
		db.execSQL("CREATE TABLE '" + "tbl_user" + "' ('" 
				+ "_id" + "' INTEGER PRIMARY KEY AUTOINCREMENT, '"
				+ "id_username" + "' TEXT, '"
				+ "fullname" + "' TEXT, '"
				+ "gender" + "' TEXT, '"
				+ "birthday" + "' TEXT, '"
				+ "email" + "' TEXT, '"
				+ "link_image" + "' TEXT, '"
				+ "type_account" + "' TEXT, '"
				+ "address" + "' TEXT, '"
				+ "latitude" + "' TEXT, '"
				+ "longitude" + "' TEXT, '"
				+ "current_address" + "' TEXT, '"
				+ "phone" + "' TEXT, '"
				+ "nickname" + "' TEXT, '"
				+ "category" + "' TEXT);");
		db.execSQL("CREATE TABLE '" + "test" + "' ('" 
				+ "_id" + "' INTEGER PRIMARY KEY AUTOINCREMENT, '"
				+ "arg0" + "' TEXT, '"
				+ "arg1" + "' TEXT, '"
				+ "arg2" + "' TEXT);");
		db.execSQL("CREATE TABLE '" + "tbl_chat" + "' ('" 
				+ "_id" + "' INTEGER PRIMARY KEY AUTOINCREMENT, '"
				+ "id_user_group" + "' TEXT, '"
				+ "content" + "' TEXT);");
		db.execSQL("CREATE TABLE '" + "tbl_location" + "' ('" 
				+ "_id" + "' INTEGER PRIMARY KEY AUTOINCREMENT, '"
				+ "id_locale" + "' TEXT, '"
				+ "latitude" + "' TEXT, '"
				+ "longitude" + "' TEXT, '"
				+ "name_address" + "' TEXT, '"
				+ "type_location" + "' TEXT, '"
				+ "description" + "' TEXT, '"				
				+ "link_image" + "' TEXT);");
		}catch(SQLException e){
			
		}
		db.close();
	}
}
